﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using JX.Core;
using JX.Core.Entity;
using JX.Infrastructure.Common;
using JX.Infrastructure.Data;
using Microsoft.IdentityModel.Tokens;

namespace JX.Dapper
{
	/// <summary>
	/// 数据库表：Contacter 的仓储实现类.
	/// </summary>
	public partial class ContacterRepositoryDapper : RepositoryDapper<ContacterEntity>,IContacterRepositoryDapper
	{
		#region 修改
		/// <summary>
		/// 修改数据。
		/// 1、检查要修改的数据中，联系人类型（UserType）如果为主联系人（企业），则修改数据库中的UserType为第二联系人（企业）。
		/// 2、修改数据。
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public override bool Update(ContacterEntity entity)
		{
			if (entity.UserType == (int)ContacterType.EnterpriceMainContacter)
			{
				Update("UserType=2", " and UserType=1 and ClientID=@ClientID", new { entity.ClientID });
			}
			return base.Update(entity);
		}
		/// <summary>
		/// 修改数据。
		/// 1、检查要修改的数据中，联系人类型（UserType）如果为主联系人（企业），则修改数据库中的UserType为第二联系人（企业）。
		/// 2、修改数据。
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public override async Task<bool> UpdateAsync(ContacterEntity entity)
		{
			if (entity.UserType == (int)ContacterType.EnterpriceMainContacter)
			{
				Update("UserType=2", " and UserType=1 and ClientID=@ClientID", new { entity.ClientID });
			}
			return await base.UpdateAsync(entity);
		}
		#endregion

		#region 删除
		/// <summary>
		/// 通过主键批量删除，同时删除U_UserText、ClientLog和RemindItem的数据。
		/// </summary>
		/// <param name="contacterID">多个ID用“,”分隔</param>
		/// <returns></returns>
		public bool DeleteByID(string contacterID)
		{
			if (string.IsNullOrEmpty(contacterID))
				return false;
			ExeSQL("DELETE FROM RemindItem WHERE CorrelativeContacter IN @ids;", new { ids = contacterID });
			ExeSQL("DELETE FROM ClientLog WHERE Contacter IN @ids;", new { ids = contacterID });
			ExeSQL("DELETE FROM U_UserText WHERE ID in @ids;", new { ids = contacterID });
			return ExeSQL("DELETE FROM Contacter WHERE ContacterID in @ids;", new { ids = contacterID }) > 0;
		}
		/// <summary>
		/// 通过主键批量删除，同时删除U_UserText、ClientLog和RemindItem的数据。
		/// </summary>
		/// <param name="contacterID">多个ID用“,”分隔</param>
		/// <returns></returns>
		public async Task<bool> DeleteByIDAsync(string contacterID)
		{
			if (string.IsNullOrEmpty(contacterID))
				return false;
			ExeSQL("DELETE FROM RemindItem WHERE CorrelativeContacter IN @ids;", new { ids = contacterID });
			ExeSQL("DELETE FROM ClientLog WHERE Contacter IN @ids;", new { ids = contacterID });
			ExeSQL("DELETE FROM U_UserText WHERE ID in @ids;", new { ids = contacterID });
			return await ExeSQLAsync("DELETE FROM Contacter WHERE ContacterID in @ids;", new { ids = contacterID }) > 0;
		}

		/// <summary>
		/// 根据UserName删除Contacter表数据，同时删除U_UserText、ClientLog和RemindItem的数据。
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public bool DeleteByUserName(string userName)
		{
			if (string.IsNullOrEmpty(userName))
				return false;
			ExeSQL("DELETE FROM RemindItem WHERE CorrelativeContacter IN (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			ExeSQL("DELETE FROM ClientLog WHERE Contacter IN (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			ExeSQL("DELETE FROM U_UserText WHERE ID = (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			return ExeSQL("DELETE FROM Contacter WHERE UserName = @UserName;", new { UserName = userName }) > 0;
		}
		/// <summary>
		/// 根据UserName删除Contacter表数据，同时删除U_UserText、ClientLog和RemindItem的数据。
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public async Task<bool> DeleteByUserNameAsync(string userName)
		{
			if (string.IsNullOrEmpty(userName))
				return false;
			ExeSQL("DELETE FROM RemindItem WHERE CorrelativeContacter IN (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			ExeSQL("DELETE FROM ClientLog WHERE Contacter IN (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			ExeSQL("DELETE FROM U_UserText WHERE ID = (SELECT ContacterID FROM Contacter WHERE UserName = @UserName);", new { UserName = userName });
			return await ExeSQLAsync("DELETE FROM Contacter WHERE UserName = @UserName;", new { UserName = userName }) > 0;
		}
		#endregion

		#region 是否存在扩展数据
		/// <summary>
		/// 是否存在扩展数据
		/// </summary>
		/// <param name="id"></param>
		/// <param name="tableName"></param>
		/// <returns></returns>
		public bool IsExistDataOption(int id, string tableName = "U_UserText")
		{
			string strSQL = "select count(*) from " + tableName + " where id=@id";
			if(GetBySQL<int>(strSQL, new { id }) > 0)
			{
				return true;
			}
			return false;
		}
		/// <summary>
		/// 是否存在扩展数据
		/// </summary>
		/// <param name="id"></param>
		/// <param name="tableName"></param>
		/// <returns></returns>
		public async Task<bool> IsExistDataOptionAsync(int id, string tableName = "U_UserText")
		{
			string strSQL = "select count(*) from " + tableName + " where id=@id";
			if (await GetBySQLAsync<int>(strSQL, new { id }) > 0)
			{
				return true;
			}
			return false;
		}
		#endregion

		#region 添加扩展数据
		/// <summary>
		/// 添加联系人扩展表数据:从contacterEntity.Fields中获取表列及列值信息
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="contacterEntity"></param>
		/// <returns></returns>
		public bool AddDataOption(string tableName, ContacterEntity contacterEntity)
		{
			if (contacterEntity.Fields == null)
				return false;
			DataRow[] dataRows = Query.GetDataRows(contacterEntity.Fields, "FieldLevel = 1");
			string filedSting = Query.GetFiledSting(dataRows);
			filedSting = filedSting + (string.IsNullOrEmpty(filedSting) ? "ID" : ", ID");
			string parametersString = Query.GetParametersString(dataRows);
			parametersString = parametersString + (string.IsNullOrEmpty(parametersString) ? "@ID" : ", @ID");
			string strSql = Query.GetInsertTableSql(tableName, filedSting, parametersString);
			var cmdParams = GetDynamicParameters(contacterEntity.Fields, "FieldLevel = 1");
			cmdParams.Add("ID",contacterEntity.ContacterID);
			return ExeSQL(strSql, cmdParams) > 0;
		}
		/// <summary>
		/// 添加联系人扩展表数据:从contacterEntity.Fields中获取表列及列值信息
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="contacterEntity"></param>
		/// <returns></returns>
		public async Task<bool> AddDataOptionAsync(string tableName, ContacterEntity contacterEntity)
		{
			if (contacterEntity.Fields == null)
				return false;
			DataRow[] dataRows = Query.GetDataRows(contacterEntity.Fields, "FieldLevel = 1");
			string filedSting = Query.GetFiledSting(dataRows);
			filedSting = filedSting + (string.IsNullOrEmpty(filedSting) ? "ID" : ", ID");
			string parametersString = Query.GetParametersString(dataRows);
			parametersString = parametersString + (string.IsNullOrEmpty(parametersString) ? "@ID" : ", @ID");
			string strSql = Query.GetInsertTableSql(tableName, filedSting, parametersString);
			var cmdParams = GetDynamicParameters(contacterEntity.Fields, "FieldLevel = 1");
			cmdParams.Add("ID", contacterEntity.ContacterID);
			return await ExeSQLAsync(strSql, cmdParams) > 0;
		}
		#endregion

		#region 修改扩展数据
		/// <summary>
		/// 修改联系人扩展表数据，不存在则添加:从contacterEntity.Fields中获取表列及列值信息
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="contacterEntity"></param>
		/// <returns></returns>
		public bool UpdateDataOption(string tableName, ContacterEntity contacterEntity)
		{
			if (IsExistDataOption(contacterEntity.ContacterID.ToInt32(), tableName))
			{
				StringBuilder builder = new StringBuilder();
				builder.Append("UPDATE ");
				builder.Append(DataSecurity.FilterBadChar(tableName));
				builder.Append(" SET ");
				DataRow[] rows = Query.GetDataRows(contacterEntity.Fields, "FieldLevel = 1");
				if (rows.Length > 0)
				{
					builder.Append(Query.GetUpdateFieldList(rows));
					builder.Append(" WHERE ID = " + contacterEntity.ContacterID.ToString());
					return ExeSQL(builder.ToString(), GetDynamicParameters(contacterEntity.Fields, "FieldLevel = 1")) > 0;
				}
				return false;
			}
			return AddDataOption(tableName, contacterEntity);
		}
		/// <summary>
		/// 修改联系人扩展表数据，不存在则添加:从contacterEntity.Fields中获取表列及列值信息
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="contacterEntity"></param>
		/// <returns></returns>
		public async Task<bool> UpdateDataOptionAsync(string tableName, ContacterEntity contacterEntity)
		{
			if (IsExistDataOption(contacterEntity.ContacterID.ToInt32(), tableName))
			{
				StringBuilder builder = new StringBuilder();
				builder.Append("UPDATE ");
				builder.Append(DataSecurity.FilterBadChar(tableName));
				builder.Append(" SET ");
				DataRow[] rows = Query.GetDataRows(contacterEntity.Fields, "FieldLevel = 1");
				if (rows.Length > 0)
				{
					builder.Append(Query.GetUpdateFieldList(rows));
					builder.Append(" WHERE ID = " + contacterEntity.ContacterID.ToString());
					return ExeSQL(builder.ToString(), GetDynamicParameters(contacterEntity.Fields, "FieldLevel = 1")) > 0;
				}
				return false;
			}
			return await AddDataOptionAsync(tableName, contacterEntity);
		}
		#endregion

		#region 删除扩展数据
		/// <summary>
		/// 删除扩展数据
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="id"></param>
		/// <returns></returns>
		public bool DeleteDataOption(string tableName, int id)
		{
			string strSQL = "delete from " + tableName + " where id=@id";
			return ExeSQL(strSQL, new { id }) > 0;
		}
		/// <summary>
		/// 删除扩展数据
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<bool> DeleteDataOptionAsync(string tableName, int id)
		{
			string strSQL = "delete from " + tableName + " where id=@id";
			return await ExeSQLAsync(strSQL, new { id }) > 0;
		}
		#endregion

		#region 得到扩展数据
		/// <summary>
		/// 根据主键得到扩展数据
		/// </summary>
		/// <param name="contacterID"></param>
		/// <param name="writeAndRead"></param>
		/// <returns></returns>
		public DataTable GetDataOption(int contacterID, WriteAndReadEnum writeAndRead = WriteAndReadEnum.None)
		{
			DataTable dtOption = new DataTable();
			if (contacterID <= 0)
				return dtOption;
			var tableName = GetBySQL<string>("select TableName from Models where ModelType=@ModelType", new { ModelType = ModelType.UserOption });
			string strSQL = "select * from "+ tableName + " where ID = @ID";
			dtOption = GetDataTableBySql(sql: strSQL, param: new { ID = contacterID }, writeAndRead: writeAndRead);
			return dtOption;
		}
		/// <summary>
		/// 根据主键得到扩展数据
		/// </summary>
		/// <param name="contacterID"></param>
		/// <param name="writeAndRead"></param>
		/// <returns></returns>
		public async Task<DataTable> GetDataOptionAsync(int contacterID, WriteAndReadEnum writeAndRead = WriteAndReadEnum.None)
		{
			DataTable dtOption = new DataTable();
			if (contacterID <= 0)
				return dtOption;
			var tableName = GetBySQL<string>("select TableName from Models where ModelType=@ModelType", new { ModelType = ModelType.UserOption });
			string strSQL = "select * from " + tableName + " where ID = @ID";
			dtOption = await GetDataTableBySqlAsync(sql: strSQL, param: new { ID = contacterID }, writeAndRead: writeAndRead);
			return dtOption;
		}
		#endregion
	}
}